package com.example.mactchoperator;

import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Romain
 */
public class ClientTCP {

	private final String host;
	private final int port;

	private final WriterTCP writerTCP;

	public ClientTCP(String host, int port) {
		this.host = host;
		this.port = port;
		writerTCP = new WriterTCP(host, port);
		Thread t = new Thread(writerTCP);
		t.start();
	}

	public boolean send(String message){
		return writerTCP.send(message);
	}

	public boolean isConnected(){
		return writerTCP.isConnected();
	}

	private class WriterTCP implements Runnable {

		private final String host;
		private final int port;

		private Socket clientSocket = null;
		private DataOutputStream output = null;
		private BufferedReader input = null;

		public WriterTCP(String host, int port) {
			this.host = host;
			this.port = port;
		}

		public boolean isConnected(){
			if(clientSocket == null){
				return false;
			}
			return clientSocket.isConnected();
		}

		@Override
		public void run() {
			while (true) {
				while (clientSocket == null || !clientSocket.isConnected()) {
					try {
						clientSocket = new Socket(host, port);
						output = new DataOutputStream(clientSocket.getOutputStream());
						input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
					} catch (IOException ex) {
						clientSocket = null;
						output = null;
						input = null;
//						Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
					}
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
			}

		}

		public boolean send(String message){
			if(output == null || clientSocket == null){
				return false;
			}
			message +="\n";
			String messageRet = null;
			try {
				output.write(message.getBytes());
				if(input == null){
					clientSocket = null;
					return false;
				}
				messageRet = input.readLine();
				if(messageRet == null){
					clientSocket = null;
					return false;
				}
			} catch (IOException ex) {
				clientSocket = null;
				output = null;
//				Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
				return false;
			}
			message = message.substring(0, message.length()-1);
			if(!messageRet.equals(message)){
				return false;
			}
			return true;
		}

	}

	public static void  main(String[] args){
		ClientTCP c = new ClientTCP("10.212.123.245", 6789);
		while(!c.isConnected())
			System.out.println(c.isConnected());
		while(true)
			System.out.println(c.send("un message"));
	}

}